//
//  UIView+Extension.swift
//  Sports
//
//  Created by yiwanjun on 2017/4/18.
//  Copyright © 2017年 Asteroid. All rights reserved.
//

import UIKit

//设置UIView 图层属性，可通过IB设置
@objc public extension UIView {
    
    /// 设置圆角
    @IBInspectable open var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    /// 设置borderWidth
    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    /// 设置borderColor
    @IBInspectable var borderColor: UIColor {
        get {
            return UIColor(cgColor: layer.borderColor ?? UIColor.white.cgColor)
        }
        set {
            layer.borderColor = newValue.cgColor
        }
    }
    
    /// 获取高度
    var height: CGFloat {
        get {
            return self.frame.size.height
        }
        
        set {
            var frame = self.frame
            frame.size.height = newValue
            self.frame = frame
        }
    }
    
    /// 获取宽度
    var width: CGFloat {
        get {
            return self.frame.size.width
        }
        
        set {
            var frame = self.frame
            frame.size.width = newValue
            self.frame = frame
        }
    }
    
    /// 获取 x 坐标
    var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        
        set {
            var frame = self.frame
            frame.origin.x = newValue
            self.frame = frame
        }
    }
    /// 获取 y 坐标
    var y: CGFloat {
        get {
            return self.frame.origin.y
        }
        
        set {
            var frame = self.frame
            frame.origin.y = newValue
            self.frame = frame
        }
    }
    
   
}

@objc public extension UIView {
    
    /// View大小
    var size: CGSize {
        get { return CGSize(width: width, height: height) }
        set (newValue) {
            var frame = self.frame
            frame.size = newValue
            self.frame = frame
            
        }
    }
    
    
    /// View中心X坐标
    var centerX: CGFloat {
        get { return self.center.x }
        set (newValue) {
            
            var center = self.center
            center.x = newValue
            self.center = center
        }
    }
    
    /// View中心Y坐标
    var centerY: CGFloat {
        get { return self.center.y }
        set (newValue) {
            var center = self.center
            center.y = newValue
            self.center = center
        }
    }
    
    /// EZSwiftExtensions
    var left: CGFloat {
        get {
            return self.x
        } set(value) {
            self.x = value
        }
    }
    
    /// EZSwiftExtensions
    var right: CGFloat {
        get {
            return self.x + self.width
        } set(value) {
            self.x = value - self.width
        }
    }
    
    /// EZSwiftExtensions
    var top: CGFloat {
        get {
            return self.y
        } set(value) {
            self.y = value
        }
    }
    
    /// EZSwiftExtensions
    var bottom: CGFloat {
        get {
            return self.y + self.height
        } set(value) {
            self.y = value - self.height
        }
    }
    
    /// 添加毛玻璃
    ///
    /// - Parameter stype: 毛玻璃样式
    func addBlurEffect(_ stype:UIBlurEffect.Style) {
        let blurEffect = UIBlurEffect(style: stype)
        let visualEffectView = UIVisualEffectView(effect: blurEffect)
        visualEffectView.frame = self.bounds
        self.addSubview(visualEffectView)
        
    }
    
}
// MARK: Layer Extensions
@objc public extension UIView {
    func findWindow() -> UIWindow? {
          // 从当前视图控制器的视图开始查找
          var view = self
          while let next = view.superview {
              view = next
              // 如果视图是 UIWindow 或其子类，则返回
              if view is UIWindow {
                  return view as? UIWindow
              }
          }
          return nil
    }
    /// EZSwiftExtensions
    func setCornerRadius(radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
    
    /// EZSwiftExtensions
    func addBorder(width: CGFloat, color: UIColor) {
        layer.borderWidth = width
        layer.borderColor = color.cgColor
        layer.masksToBounds = true
    }
    
    /// EZSwiftExtensions
    func addBorderTop(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
    }
    
    //TODO: add to readme
    /// EZSwiftExtensions
    func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) {
        addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color)
    }
    
    /// EZSwiftExtensions
    func addBorderBottom(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
    }
    
    /// EZSwiftExtensions
    func addBorderLeft(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
    }
    
    /// EZSwiftExtensions
    func addBorderRight(size: CGFloat, color: UIColor) {
        addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
    }
    
    /// EZSwiftExtensions
    fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: x, y: y, width: width, height: height)
        layer.addSublayer(border)
    }
    //TODO: add this to readme
    /// EZSwiftExtensions
    func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
        let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = fillColor.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = strokeWidth
        self.layer.addSublayer(shapeLayer)
    }
    //TODO: add this to readme
    /// EZSwiftExtensions
    func drawStroke(width: CGFloat, color: UIColor) {
        let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2)
        let shapeLayer = CAShapeLayer ()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = width
        self.layer.addSublayer(shapeLayer)
    }
    
    func addBorderAndCornerRadius(width: CGFloat, color: UIColor, radius: CGFloat) {
        layer.cornerRadius = radius
        layer.borderWidth = width
        layer.borderColor = color.cgColor
        layer.masksToBounds = true
    }
    
    /// 添加渐变层
    /// - Parameters:
    ///   - startColor: 开始颜色
    ///   - endColor: 结束颜色
    ///   - dirention: 渐变方向
    @discardableResult
    func gradLayer(startColor: UIColor, endColor: UIColor, dirention: UIDeviceOrientation, inset: UIEdgeInsets = .zero)  -> CAGradientLayer{
        self.gradLayer(startColor: startColor, endColor: endColor, dirention: dirention, at: 0,inset: inset)
    }
    
    /// 在Navigationbar上添加渐变层
    /// - Parameters:
    ///   - startColor: 开始颜色
    ///   - endColor: 结束颜色
    ///   - dirention: 渐变方向
    func gradLayerForNavigationbar(startColor: UIColor, endColor: UIColor, dirention: UIDeviceOrientation){
        self.gradLayer(startColor: startColor, endColor: endColor, dirention: dirention, at: 2)
    }
    
    /// 隐藏渐变层
    func hiddenGraindLayer(){
        self.layer.sublayers?.forEach({ (layer) in
            if let _ = layer as? CAGradientLayer{
                layer.removeFromSuperlayer()
            }
        })
    }
    
    /// 添加渐变层
    /// - Parameters:
    ///   - startColor: 开始颜色
    ///   - endColor: 结束颜色
    ///   - dirention: 渐变方向
    ///   - index: 渐变层的位置
    ///   注意：很多时候不能获取到真实frame，所以在layoutSubviews中使用这个方法，通过传入同一个Index，避免出现多个渐变层。这个方法虽有浪费，但是可接受
    @discardableResult
    func gradLayer(startColor: UIColor, endColor: UIColor, dirention: UIDeviceOrientation, at index: Int, inset: UIEdgeInsets = .zero) -> CAGradientLayer{
    
        let gradLayer = CAGradientLayer()
        gradLayer.colors = [startColor.cgColor, endColor.cgColor]
        gradLayer.frame = self.bounds.inset(by: inset)
        switch dirention {
        case .portrait:
            gradLayer.startPoint = CGPoint(x: 0.5, y: 0)
            gradLayer.endPoint = CGPoint(x: 0.5, y: 1)
        case .landscapeLeft:
            gradLayer.startPoint = CGPoint(x: 0, y: 0.5)
            gradLayer.endPoint = CGPoint(x: 1, y: 0.5)
        default:
            gradLayer.startPoint = CGPoint(x: 0, y: 0)
            gradLayer.endPoint = CGPoint(x: 1, y: 1)
        }
        if let sublayers = layer.sublayers, sublayers.count <= (index + 1) {
            layer.sublayers?.remove(at: index)
        }
        self.layer.insertSublayer(gradLayer, at: UInt32(index))
        return gradLayer
    }
    
    /// 通过颜色生成图片
    /// - Parameter color: 颜色
    /// - Returns: UIImage
    func colorImage(color: UIColor) -> UIImage {
        UIGraphicsBeginImageContext(self.bounds.size)
        
        //// General Declarations
        let context = UIGraphicsGetCurrentContext()!
        
        //// Rectangle Drawing
        let rectanglePath = UIBezierPath(rect: self.bounds)
        context.saveGState()
        color.setFill()
        rectanglePath.fill()
        
        context.restoreGState()
        
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 获取view关联的第一个UIViewController
    /// - Returns: UIViewController
    func viewController() -> UIViewController?{
        weak var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
    
    /// 获取view关联的第一个UINavigationController
    /// - Returns: UINavigationController
    func navigationViewController() -> UINavigationController?{
        weak var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UINavigationController {
                return viewController
            }
        }
        return nil
    }
    
    /// 生成渐变色的图片
    /// - Parameters:
    ///   - startColor: 开始颜色
    ///   - endColor: 结束颜色
    ///   - dirention: 渐变方向
    /// - Returns: UIImage
    func gradientImage(startColor: UIColor, endColor: UIColor, dirention: UIDeviceOrientation) -> UIImage{
        
        
        UIGraphicsBeginImageContext(self.bounds.size)
        
        //// General Declarations
        let context = UIGraphicsGetCurrentContext()!
        
        //// Gradient Declarations
        let gradient = CGGradient(colorsSpace: nil, colors: [startColor.cgColor, endColor.cgColor] as CFArray, locations: [0, 1])!
        
        //// Rectangle Drawing
        let rectanglePath = UIBezierPath(rect: self.bounds)
        context.saveGState()
        rectanglePath.addClip()
        switch dirention {
        case .portrait:
            context.drawLinearGradient(gradient, start: CGPoint(x: self.frame.size.width/2, y: 0), end: CGPoint(x: self.frame.size.width/2, y: self.frame.size.height), options: [])
        case .landscapeLeft:
            context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: self.frame.size.height/2), end: CGPoint(x: self.frame.size.width, y: self.frame.size.height/2), options: [])
        default:
            context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: self.frame.size.width, y: self.frame.size.height), options: [])
        }
        
        context.restoreGState()
        
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
 
extension UIView {
    /// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight]
    public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.backgroundColor = UIColor.white.cgColor
        self.layer.mask = mask
    }
    
    /// EZSwiftExtensions - Mask square/rectangle UIView with a circular/capsule cover, with a border of desired color and width around it
    public func roundView(withBorderColor color: UIColor? = nil, withBorderWidth width: CGFloat? = nil) {
        self.setCornerRadius(radius: min(self.frame.size.height, self.frame.size.width) / 2)
        self.layer.borderWidth = width ?? 0
        self.layer.borderColor = color?.cgColor ?? UIColor.clear.cgColor
    }
    
    /// EZSwiftExtensions - Remove all masking around UIView
    public func nakedView() {
        self.layer.mask = nil
        self.layer.borderWidth = 0
    }
}


public extension UIView {
    /// 设置指定方向的圆角
    /// - Parameters:
    ///   - corner: 圆角的方向
    ///   - cornerRadius: 圆角的大小
    func setMaskedCorner(_ corner: UIRectCorner, cornerRadius: Int) {
        let path = UIBezierPath(roundedRect: self.bounds,
                                byRoundingCorners: corner,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let layer = CAShapeLayer()
        layer.frame = self.bounds
        layer.path = path.cgPath
        layer.fillColor = UIColor.white.cgColor
        self.layer.mask = layer
    }
    
    /// 获取一个带系统ActivityIndicator的视图
    /// - Parameter view: ActivityIndicator的父视图
    /// - Returns: 带系统ActivityIndicator的视图
    static func showLoading(in view: UIView?) -> UIView? {
        guard let view = view else {
            return nil
        }
        let container = UIView(frame: view.frame)
        container.tag = 9527
        container.backgroundColor = UIColor.white
        
        let indicator = UIActivityIndicatorView(style: .gray)
        indicator.center = CGPoint(x: container.width/2, y: container.height/2)
        indicator.startAnimating()
        container.addSubview(indicator)
        
        view.addSubview(container)
        return container
    }
}



extension UIView
{
    
    /// 复制一个UIView
    /// - Returns: UIView
    func copyView<T: UIView>() -> T {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
    }
}


extension UIView {
    // MARK: - UIView 转 UIImage
    public func convertImage() -> UIImage {
        /*
         下面方法
         第一个参数表示区域大小。
         第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。
         第三个参数就是屏幕密度了
         */
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        self.layer.render(in: context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}
